package com.learn.boot.datasource.controller;


import com.learn.boot.datasource.config.DataSourceContextHolder;
import com.learn.boot.datasource.domain.User;
import com.learn.boot.datasource.service.ChangeDataSourceService;
import com.learn.boot.datasource.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private ChangeDataSourceService changeDataSourceService;

    @Resource
    private UserService userService;


    @GetMapping("/test")
    public String test(String dataSourceId) {
        changeDataSourceService.changeDS(dataSourceId);
        List<User> users1 = userService.list();
        users1.stream().forEach(System.out::println);

        dataSourceId = "learn_mybatis";
        changeDataSourceService.changeDS(dataSourceId);
        List<User> users2 = userService.list();
        users2.stream().forEach(System.out::println);
        //切回主数据源
        DataSourceContextHolder.removeDataSource();
        return "ok";
    }
}
